package com.shamine.kuaiqiao.blink.detail

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.chrisbanes.photoview.PhotoView
import com.shamine.kuaiqiao.blink.detail.play.Play
import com.shamine.kuaiqiao.blink.data.Gallery
import com.shamine.kuaiqiao.blink.data.Photo
import com.shamine.kuaiqiao.blink.event.EventSavePhoto
import com.theartofdev.edmodo.cropper.CropImage
import com.theartofdev.edmodo.cropper.CropImageView
import kotlinx.android.synthetic.main.activity_detail.*
import kotlinx.android.synthetic.main.layout.*
import com.shamine.kuaiqiao.blink.R
import com.shamine.kuaiqiao.blink.basic.BaseActivity
import com.shamine.kuaiqiao.blink.basic.BlinkApplication
import com.shamine.kuaiqiao.blink.basic.GlideApp
import com.shamine.kuaiqiao.blink.event.EventGalleryDeleted
import com.shamine.kuaiqiao.blink.events.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File

class DetailActivity : BaseActivity() {

    private lateinit var gallery: Gallery
    private lateinit var worker: Worker
    private lateinit var adapter: PhotosAdapter
    private lateinit var manager: GridLayoutManager
    //要删除的照片再列表中的位置
    private var dyingPhotoPosition = 0
    //是否第一次加载
    private var virginLoad = true
    //最后一张日期
    private lateinit var date: String
    private lateinit var dialog: Dialog
    private var emptyGallery: Boolean = false
    private var setWallpaper = false
    //要设置壁纸的photo
    private lateinit var wallpaperPhoto: Photo
    private val SET_WALLPAPER = 1230
    private lateinit var photoView: PhotoView
    private lateinit var zoomView: Dialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)
        EventBus.getDefault().register(this)
        setSupportActionBar(toolbar)
        supportActionBar?.title = gallery.title
        toolbar.setTitleTextColor(ContextCompat.getColor(this,R.color.white))
        worker = Worker(this,gallery)
        dialog = getDialog(this)

        zoomView = Dialog(this, R.style.DialogBigPhoto)
        zoomView.setContentView(R.layout.dialog_photo)
        zoomView.setCanceledOnTouchOutside(true)
        photoView = zoomView.findViewById(R.id.bigPhoto)

        initAdapter()
        if (isConnected()){
            error.text = getString(R.string.status_getting_data)
            worker.getPhotos(virginLoad,"2010-12-29 11:02:40")
        } else error.text = getString(R.string.status_device_offline)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_detail,menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when(item?.itemId){
            R.id.action_new -> cropFrom()
            R.id.action_play -> {
                EventBus.getDefault().postSticky(EventGallery(Play::class.java,gallery))
                goTo(Play::class.java,false)
            }
            R.id.action_delete -> {
                AlertDialog.Builder(this).setTitle(getString(R.string.title_delete_gallery))
                        .setPositiveButton(getString(R.string.btn_ok)) { _, _ ->
                            //删除相册
                            dialog.show()
                            worker.deleteGallery(gallery) }
                        .setNegativeButton(getString(R.string.btn_cancel)){_, _ -> }
                        .show()
            }
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 开始裁剪照片，选择照片来源
     */
    private fun cropFrom() {
        CropImage.startPickImageActivity(this)
    }



    //开始裁剪选择的图片
    private fun startCropping(imageUri: Uri) {
        CropImage.activity(imageUri)
                .setAllowRotation(true)
                .setAllowFlipping(false)
                .setActivityTitle(getString(R.string.title_activity_crop))
                .setActivityMenuIconColor(ContextCompat.getColor(this,R.color.colorPrimary))
                .setAspectRatio(9,16)
                .setCropShape(CropImageView.CropShape.RECTANGLE)
                .setMinCropResultSize(900,1600)
                .setAutoZoomEnabled(true)
                .start(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK)
        when(requestCode){
            CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE -> {
                val imageUri = CropImage.getPickImageResultUri(this, data)
                    startCropping(imageUri)
            }
            CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE ->{
                val result = CropImage.getActivityResult(data)
                if (resultCode == RESULT_OK) {
                    //resultUri.path: /data/user/0/com.shamine.kuaiqiao.blink/cache/cropped1370004873.jpg
                    dialog.show()
                    worker.upload(result.uri.path)
                } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                    val error = result.error
                    toast(this,error.message.toString())
                }
            }
        }
    }

    /**
     * 获取点击的相册
     */
    @Subscribe(sticky = true)
    fun galleryReceiver(event: EventGallery){
        if (event.cls == javaClass) this.gallery = event.gallery
    }

    /**
     * 删除相册结果
     */
    @Subscribe
    fun galleryDeleted(event: EventGalleryDeleted){
        dialog.dismiss()
        if (event.deleted){
            toast(this,getString(R.string.toast_success))
            finish()
        } else toast(this,getString(R.string.toast_fail)+event.msg)
    }

    /**
     * 照片上传成功
     */
    @Subscribe
    fun photoUpload(event: EventPhotoUpload){
        dialog.dismiss()
        if (event.done) {
            //如果是第一张
            if (emptyGallery) {
                error.visibility = View.GONE
            }
            gallery.size = event.size
            adapter.setSize(event.size)
            adapter.addData(0,event.photo)
            adapter.loadMoreEnd()
            list.smoothScrollToPosition(0)
        } else toast(this,event.msg)
    }

    /**
     * 照片查询结果
     */
    @Subscribe
    fun photosReceiver(event: EventPhotos){
        if (event.done){
            if (event.photos.size == 0) {
                //第一次加载为0
                if (virginLoad) {
                    emptyGallery = true
                    error.text = getString(R.string.status_no_photos)
                }
                //恰好数量时18的倍数，非第一次加载不为0,到底了
                adapter.loadMoreEnd()
            } else {//结果不等于0，
                error.visibility = View.GONE
                date = event.photos[event.photos.size - 1].createdAt
                if (virginLoad) {
                    adapter.setNewData(event.photos)
                } else {
                    adapter.addData(event.photos)
                }
                if (event.photos.size < 18){
                    adapter.loadMoreEnd()
                }else {
                    adapter.loadMoreComplete()
                }
            }
        }else {
            toast(this,event.msg)
            if (adapter.itemCount > 0) adapter.loadMoreFail() else error.text = event.msg
        }
        virginLoad = false
    }

    /**
     * 删除照片 结果
     */
    @Subscribe
    fun photoDeleted(event: EventPhotoDeleted){
        dialog.dismiss()
        adapter.setSize(event.size)
        if (event.done) adapter.remove(dyingPhotoPosition) else toast(this,event.msg)
        adapter.notifyDataSetChanged() //仿佛没有动画一般
    }

    /**
     * 保存照片到本地 结果
     */
    @Subscribe
    fun savePhoto(event: EventSavePhoto){
        dialog.dismiss()
        if (event.done) {
            if (setWallpaper) setWallpaper(wallpaperPhoto)
            toast(this,getString(R.string.toast_success))
        }
        else toast(this,getString(R.string.toast_fail) +":"+ event.msg)
    }

    /**
     * 初始化adapter
     */
    private fun initAdapter() {
        adapter = PhotosAdapter(this,gallery.size)

        adapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val photo = adapter.getItem(position) as Photo
            zoomView.show()
            GlideApp.with(this@DetailActivity).load(photo.photo.fileUrl).into(photoView)
        }

        adapter.onItemLongClickListener = BaseQuickAdapter.OnItemLongClickListener { adapter, _, position ->
            val photo = adapter.getItem(position) as Photo
            AlertDialog.Builder(this@DetailActivity)
                    .setItems(R.array.delete_photo, { _, itemId ->
                        when(itemId){
                        //删除照片
                            0 -> {
                                dialog.show()
                                dyingPhotoPosition = position
                                worker.deletePhoto(photo)
                            }
                        //保存照片 权限检查
                            1 -> {
                                dialog.show()
                                worker.savePhoto(photo)
                            }
                        //设为壁纸
                            2 -> {
                                dialog.show()
                                setWallpaper = true
                                wallpaperPhoto = photo
                                worker.savePhoto(photo)
                            }
                        }
                    }).show()
            false
        }

        manager = GridLayoutManager(this,3, GridLayoutManager.VERTICAL,false)
        //自动加载更多 todo
        adapter.setOnLoadMoreListener({
            worker.getPhotos(virginLoad, date)
        },list)
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        list.hasFixedSize()
        list.layoutManager = manager
        list.adapter = adapter
    }

    //设置壁纸
    private fun setWallpaper(photo: Photo) {
        setWallpaper = false
        val file = File(BlinkApplication.SAVE_PATH,"${photo.createdAt}.jpg")
        val bitmap = BitmapDrawable.createFromPath(file.path)
        val intent = Intent(Intent.ACTION_ATTACH_DATA)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.putExtra("mimeType", "image/*")
        val uri = Uri.parse(MediaStore.Images.Media
                .insertImage(this.contentResolver,
                        (bitmap as BitmapDrawable).bitmap, null, null))
        intent.data = uri
        ActivityCompat.startActivityForResult(this, intent, SET_WALLPAPER, null)
        //删除保存再app文件夹的照片
        file.delete()
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    @Subscribe
    override fun onSignOut(event: EventSignOut) {
        EventBus.getDefault().unregister(this)
        finish()
    }
}
